package com.sgb.kjwl.view.ui.fragment.self;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AppFragmentProprietaryDriverBinding;
import com.sgb.kjwl.model.entity.self.MotorcadeSimpleEntity;
import com.sgb.kjwl.model.entity.self.ProprietaryDriverEntity;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.activity.transport.company.AddProprietaryFleetActivity;
import com.sgb.kjwl.view.ui.adapter.self.ProprietaryDriverListAdapter;
import com.sgb.kjwl.view.widget.transport.ChooseMotorcadeDialog;
import com.sgb.kjwl.viewmodel.self.driver.ProprietaryDriverFraModel;
import com.sgb.link.router.PathDriver;
import com.swgk.core.common.base.BaseFragment;
import com.swgk.core.dialog.RoundDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * Describe:    自营司机列表
 * Author:  yangLei
 * Date:    2021/10/11
 */
public class ProprietaryDriverFragment extends BaseFragment<ProprietaryDriverFraModel, AppFragmentProprietaryDriverBinding> {
    //数据状态:1 邀请中 2 已拒绝 3 已同意 4 已解除
    private Integer mStatus = 0;
    private ProprietaryDriverListAdapter driverAdapter;
    private List<ProprietaryDriverEntity> data = new ArrayList<>();

    private ChooseMotorcadeDialog editDialog;
    private int editIndex;
    private boolean isLoadMore = false;

    public static ProprietaryDriverFragment newInstance(int type) {
        Bundle args = new Bundle();
        args.putInt(RouterKey.TYPE, type);
        ProprietaryDriverFragment fragment = new ProprietaryDriverFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int layoutId() {
        return R.layout.app_fragment_proprietary_driver;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(ProprietaryDriverFraModel.class);
    }

    @Override
    protected void init() {
        initPage();
        initEvent();
        initViews();

        mViewModel.requestDriverList(getContext(), mStatus, isLoadMore);
    }

    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    private void initViews() {
        driverAdapter = new ProprietaryDriverListAdapter(getContext(), data);
        mBinding.rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerDecoration.builder(_mActivity)
                .colorRes(R.color.transparent)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvList);
        mBinding.rvList.setAdapter(driverAdapter);
        driverAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (data.size() > position)
                itemClick(view, position);
        });

        mBinding.rvList.setVisibility(View.VISIBLE);
        mBinding.emptyLay.setVisibility(View.GONE);

        mBinding.smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                mBinding.smartRefresh.finishLoadMore(200);
                refreshList(true);
            }
        });
        mBinding.smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                mBinding.smartRefresh.finishRefresh(200);
                refreshList(false);
            }
        });
    }

    private void initPage() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            int type = getArguments().getInt(RouterKey.TYPE, 0);
            switch (type) {
                case 1:
                case 2:
                case 3:
                case 4:
                    mStatus = type;
                    break;

                default:
                    mStatus = null;
                    break;
            }
        }
    }

    private void initEvent() {
        mViewModel.driverListLD.observe(this, proprietaryDriverEntities -> refreshData(proprietaryDriverEntities));
        mViewModel.motorcadeListLD.observe(this, list -> {
            motorcadeListRequestResult(list);
        });

        mViewModel.unbindLD.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean != null && aBoolean) {//关系解绑成功
                    EventBus.getDefault().postSticky(MenuEvent.make(EventConstant.EVENT_REFRESH_PRO_DRIVER, null));
                }
            }
        });

        mViewModel.deleteLD.observe(this, aBoolean -> {
            if (aBoolean != null && aBoolean) {//删除成功
                EventBus.getDefault().postSticky(MenuEvent.make(EventConstant.EVENT_REFRESH_PRO_DRIVER, null));
            }
        });
    }

    private void refreshList(boolean b) {
        isLoadMore = b;
        mViewModel.requestDriverList(getContext(), mStatus, isLoadMore);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_PRO_DRIVER) {
            refreshList(false);
        }
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 去编辑所属车队
     *
     * @param list
     */
    private void motorcadeListRequestResult(List<MotorcadeSimpleEntity> list) {
        if (list == null || list.size() < 1) {
            //没有车队时弹窗提示
            new RoundDialog.Builder(getContext())
                    .title("提示")
                    .content("添加司机需要选择车队，当前无可用车队，请先至“车队管理”添加自营车队")
                    .confirm("确定")
                    .singleBtn(true)
                    .cancelable(false)
                    .show();
        } else {
            //有车队可选
            ChooseMotorcadeDialog.setDefaultItem(list, data.get(editIndex).getMotorcadeNo());
            if (editDialog == null) {
                editDialog = ChooseMotorcadeDialog.newInstance(getContext(), 0, list);
                editDialog.setResultListener(entity -> {
                    //修改成功后刷新数据
                    if (data.size() > editIndex) {
                        if (entity != null && !TextUtils.isEmpty(entity.getMotorcadeNo()) && !TextUtils.isEmpty(entity.getMotorcadeName())) {
                            data.get(editIndex).setMotorcadeNo(entity.getMotorcadeNo());
                            data.get(editIndex).setMotorcadeName(entity.getMotorcadeName());
                        } else {
                            data.get(editIndex).setMotorcadeNo("");
                            data.get(editIndex).setMotorcadeName("");
                        }
                        driverAdapter.notifyDataSetChanged();
                    }
                });
            } else {
                editDialog.setMotorcades(list);
            }
            editDialog.show();
            editDialog.setTitle("编辑所属车队");
            editDialog.setDriverInfo(data.get(editIndex));
        }
    }

    private void itemClick(View view, int position) {
        if (data.size() <= position)
            return;
        //需要记录点击的位置，便于数据更新后回调显示
        editIndex = position;
        ProprietaryDriverEntity entity = data.get(position);
        switch (view.getId()) {
            case R.id.edit_btn:
                if (entity == null)
                    return;
                //根据有无车队做判断，是去编辑车队还是添加车队
                if (entity.isHasMotorcade()) {
                    //有车队请求车队信息
                    mViewModel.requestMotorcadeList(getContext());
                } else {
                    //没有车队去添加
                    AddProprietaryFleetActivity.start(getActivity(), true);
                }

                break;

            case R.id.unbind_btn:
                if (entity == null || entity.getLinkState() == null)
                    return;
                switch (entity.getLinkState()) {
                    case 3://已同意，需要解除关系
                        if (entity != null && !TextUtils.isEmpty(entity.getName()) && !TextUtils.isEmpty(entity.getNo())) {
                            new RoundDialog.Builder(getContext())
                                    .title("提示")
                                    .content("解除关系后，绑定该司机的车辆将被解绑。您确定要解除关系吗？")
                                    .confirm("确定")
                                    .cancel("取消")
                                    .singleBtn(false)
                                    .cancelable(false)
                                    .confirmCallback(v -> mViewModel.unbindDriver(entity.getNo()))
                                    .show();
                        }
                        break;

                    case 2:
                    case 4:
                        //已拒绝和已解除，直接进行删除
                        if (entity != null && !TextUtils.isEmpty(entity.getName()) && !TextUtils.isEmpty(entity.getNo())) {
                            new RoundDialog.Builder(getContext())
                                    .title("提示")
                                    .content("您确定要删除司机" + entity.getName() + "吗？")
                                    .confirm("确定")
                                    .cancel("取消")
                                    .singleBtn(false)
                                    .cancelable(false)
                                    .confirmCallback(v -> mViewModel.deleteDriver(entity.getNo()))
                                    .show();
                        }
                        break;
                }
                break;

            case R.id.item_layout:
                if (!TextUtils.isEmpty(entity.getNo()))
                    ARouter.getInstance().build(PathDriver.ProprietaryDriverDetailsActivity)
                            .withString(RouterKey.ID, entity.getNo())
                            .navigation(getContext());
                break;
        }
    }

    /**
     * 更新数据
     *
     * @param driverEntities
     */
    private void refreshData(List<ProprietaryDriverEntity> driverEntities) {
        if (driverEntities == null || driverEntities.size() == 0) {
            if (!isLoadMore) {
                mBinding.emptyLay.setVisibility(View.VISIBLE);
                mBinding.rvList.setVisibility(View.GONE);
            }
        } else {
            mBinding.emptyLay.setVisibility(View.GONE);
            mBinding.rvList.setVisibility(View.VISIBLE);
            if (!isLoadMore) {
                data.clear();
            }
            data.addAll(driverEntities);
            driverAdapter.notifyDataSetChanged();
        }
    }
}
